package com.wechatmall.api.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.wechatmall.api.pojo.dto.MechrantDto;
import com.wechatmall.api.pojo.entity.Merchants;
import com.wechatmall.api.security.config.JwtConfig;
import com.wechatmall.api.security.entity.LoginUser;
import com.wechatmall.api.security.util.JwtUtil;
import com.wechatmall.api.service.IMerchantsService;
import com.wechatmall.api.service.IUserService;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zpc
 * @since 2025-09-21 22:09:20
 */
@Service
@AllArgsConstructor
public class UserServiceImpl implements IUserService {

    private final AuthenticationManager authenticationManager;
    private final IMerchantsService merchantsService;
    private final JwtConfig  jwtConfig;


    @Override
    public String login(String username, String password) {
        UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authentication = authenticationManager.authenticate(auth);
        if(authentication == null){
            return null;
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return JwtUtil.sign(JSON.toJSONString(loginUser),jwtConfig);
    }

    @Override
    public String register(MechrantDto userDto) {
        Merchants merchants = new Merchants();
        BeanUtil.copyProperties(userDto,merchants);
        BCryptPasswordEncoder crypt = new BCryptPasswordEncoder();
        merchants.setPassword(crypt.encode(userDto.getPassword()));
        boolean result = merchantsService.save(merchants);
        if(result){
            return "注册成功";
        }
        return "注册失败";
    }

    @Override
    public void wechatLogin(String code) {
        // TODO: 微信登录
    }
}
